package com.mjlf.mjatis.excutor;

import com.mjlf.mjatis.config.Configuration;
import com.mjlf.mjatis.mapper.MapperMethod;
import com.mjlf.mjatis.result.ResutUtil;

import java.lang.reflect.InvocationTargetException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;

/**
 * @ClassName DefaultExecutor
 * @Author mjlft
 * @Date 2020/6/19 21:46
 * @Version 1.0
 * @Description 默认执行器
 */
public class DefaultExecutor extends AbstractExecutor {


    @Override
    public int update(Configuration configuration, MapperMethod mapperMethod) throws SQLException {
        PreparedStatement preparedStatement = getStatement(configuration, mapperMethod);
        int result = preparedStatement.executeUpdate();
        preparedStatement.close();
        return result;
    }

    @Override
    public <T> T query(Configuration configuration, MapperMethod mapperMethod, Class<T> tClass) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {
        PreparedStatement preparedStatement = getStatement(configuration, mapperMethod);
        ResultSet resultSet = preparedStatement.executeQuery();

        //结果集处理
        T result = ResutUtil.parseResult(configuration, tClass, resultSet);
        return result;
    }

    private PreparedStatement getStatement(Configuration configuration, MapperMethod mapperMethod) throws SQLException {

        PreparedStatement preparedStatement = configuration.getDataSource().getConnection().prepareStatement(mapperMethod.getSqlBound().getSql());
        if (mapperMethod.getSqlBound().getParams() != null) {
            Object[] params = mapperMethod.getSqlBound().getParams().toArray();
            for (int i = 1; i <= params.length; i++) {
                preparedStatement.setObject(i, params[i - 1]);
            }
        }
        return preparedStatement;
    }
}
